//
//  HTTPClient.m
//  PropertyManager
//
//  Created by TNG on 2018/8/31.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "HTTPClient.h"

@implementation HTTPClient

+(HTTPClient *)shareClient
{
    static HTTPClient * http = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        http = [[HTTPClient alloc] init];
    });
    //        https://blog.csdn.net/czh880410/article/details/52057501
    return http;
}

-(void)requestWithPath:(NSString *)path AndParams:(NSDictionary *)params AndReturnBlock:(returnDic)block AndFailMessage:(sendFailMessage)failMessage
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    dispatch_queue_t queue = dispatch_queue_create("netWork", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        
        NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,path]];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        request.timeoutInterval = 15;
        request.HTTPMethod = @"POST";
        
        NSData * json = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        request.HTTPBody = json;
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
        [request setValue:SFMToken forHTTPHeaderField:@"X-AUTH-TOKEN"];
        
        NSSLog(@"url === %@ \n params=== %@",url,params);
        
        NSURLSession* session = [NSURLSession sharedSession];
        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                NSSLog(@"访问失败=====\n localizedFailureReason=====%@\n userInfo===%@\nlocalizedDescription===%@\n",error.localizedFailureReason,error.userInfo,error.localizedDescription);
                return ;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            });
            if([response isKindOfClass:[NSHTTPURLResponse class]]) {
                NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
                NSSLog(@"httpResponse=== %d",(int)httpResponse.statusCode);
                if (httpResponse.statusCode != 200) {
                    return;
                }
            }
            
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSSLog(@"path == %@\n dic === %@",path,dic);
            NSString * codeStr = [NSString stringWithFormat:@"%@",dic[@"respCode"]];
            if ([codeStr isEqualToString:@"0"]) {
                block(dic);
            }else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failMessage(dic[@"respMsg"],codeStr);
                });
            }
        }];
        [task resume];
    });
}

-(void)requestWithPath:(NSString *)path AndReturnBlock:(returnDic)block AndFailMessage:(sendFailMessage)failMessage
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    //1、网址
    NSString *urlstring= [NSString stringWithFormat:@"%@%@",BASE_URL,path];
    NSSLog(@"urlstring=== %@",urlstring);

    //如果URL网址里有中文，要先转成utf8
    NSString *urlstr= [urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //2、创建URL
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstr]];
    request.timeoutInterval = 15;
    //3、创建网络请求
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"*/*" forHTTPHeaderField:@"Accept"];
    [request setValue:SFMToken forHTTPHeaderField:@"X-AUTH-TOKEN"];
    [request setValue:@"GET" forHTTPHeaderField:@""];
    NSLog(@"SFMToken=%@",SFMToken);
    //4、创建get请求
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSSLog(@"访问失败=====\n localizedFailureReason=====%@\n userInfo===%@\nlocalizedDescription===%@\n",error.localizedFailureReason,error.userInfo,error.localizedDescription);
            return ;
        }
        
        if([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response;
            NSSLog(@"httpResponse=== %d",(int)httpResponse.statusCode);
            if (httpResponse.statusCode != 200) {
                [SVProgressHUD ShowErrorMessage:[NSString stringWithFormat:@"错误码：%d",(int)httpResponse.statusCode]];
                return;
            }
        }
        
        id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary * dic;
        if ([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSMutableDictionary class]]) {
            dic = (NSDictionary *) obj;
        }
        NSSLog(@"dic === %@",dic);
        NSString * codeStr = [NSString stringWithFormat:@"%@",dic[@"respCode"]];
        if ([codeStr isEqualToString:@"0"]) {
            block(dic);
        }else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                failMessage(dic[@"respMsg"],codeStr);
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
    }];
    //5、执行请求
    [dataTask resume];
}




@end
